var express = require('express')
var md5 = require('blueimp-md5')
var sd = require('silly-datetime')
var multer = require('multer')
var fs = require('fs')
var mysql = require('./database.js')

var router = express.Router()

/* 上传图片start */
var createFolder = function (folder) {
    try {
        fs.accessSync(folder);
    } catch (e) {
        fs.mkdirSync(folder);
    }
};

var uploadFolder = './upload/img';

createFolder(uploadFolder);

// 通过 filename 属性定制
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, uploadFolder);    // 保存的路径，备注：需要自己创建
    },
    filename: function (req, file, cb) {
        // 将保存文件名设置为 字段名 + 时间戳，比如 logo-1478521468943
        cb(null, file.originalname);
    }
});

// 通过 storage 选项来对 上传行为 进行定制化
var upload = multer({ storage: storage })
/* 上传图片end */

/* 渲染主页 */
router.get('/', function (req, res) {

    var page = req.query.sum || 1

    var start = (page - 1) * 8

    var end = page * 8

    var queryCount = 'SELECT COUNT(*) AS notesNum FROM notes'

    var user = req.session.data

    if (user) {

        var queryCount1 = 'SELECT COUNT(*) AS notesNum FROM notes WHERE userID=' + user[0].ID

        var query = 'SELECT * FROM users WHERE ID=' + mysql.escape(user[0].ID)

        mysql.query(query, function (err, data) {
            if (err) {
                console.log(err)
                return
            }

            var query = 'SELECT * FROM notes WHERE userID=' + mysql.escape(user[0].ID) + ' ORDER BY ID DESC LIMIT ' + start + ',' + end
            mysql.query(query, function (err, rows) {
                if (err) {
                    console.log(err)
                    return
                }

                mysql.query(queryCount1, function (err, getDataNum) {
                    if (err) {
                        console.log(err)
                        return
                    }

                    var num = getDataNum[0].notesNum
                    var pageNum = Math.ceil(num / 8)

                    res.render('home.html', {
                        user: data[0],
                        getInfo: data[0],
                        note: rows,
                        pageNum: pageNum
                    })
                })
            })
        })

    } else {
        var query = 'SELECT * FROM notes ' + 'ORDER BY ID DESC LIMIT ' + start + ',' + end
        mysql.query(query, function (err, rows) {
            if (err) {
                console.log(err)
                return
            }

            mysql.query(queryCount, function (err, getDataNum) {
                if (err) {
                    console.log(err)
                    return
                }

                var num = getDataNum[0].notesNum
                var pageNum = Math.ceil(num / 8)

                res.render('home.html', {
                    note: rows,
                    pageNum: pageNum
                })
            })
        })
    }
})

/* 渲染添加笔记页面 */
router.get('/addNote', function (req, res) {
    res.render('addNote.html')
})

/* 添加笔记请求 */
router.post('/addNote', upload.single('logo'), function (req, res) {
    var body = req.body
    var file = req.file
    var time = sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
    body.create_time = time

    var title = body.title
    var content = body.content
    var create_time = body.create_time
    var upload = file.destination + '/' + file.originalname
    var userID = req.session.data[0]

    var query = 'INSERT notes SET title=' + mysql.escape(title) + ',content=' + mysql.escape(content) + ',create_time=' + mysql.escape(create_time) + ',upload=' + mysql.escape(upload) + ',userID=' + mysql.escape(userID.ID)

    mysql.query(query, function (err, data) {
        if (err) {
            res.render('addNote.html', {
                err: '标题重复了!'
            })
            return
        }

        res.redirect('/')
    })
})

/* 删除笔记 */
router.get('/deleteNote', function (req, res) {

    var id = req.query.id.replace(/"/g, '')

    var query = 'DELETE FROM notes WHERE ID=' + mysql.escape(id)

    mysql.query(query, function (err, data) {
        if (err) {
            console.log(err)
            return
        }

        res.redirect('/')
    })
})

/* 渲染编辑笔记页面 */
router.get('/editNote', function (req, res) {

    var id = req.query.id.replace(/"/g, '')

    var query = 'SELECT * FROM notes WHERE ID=' + mysql.escape(id)

    mysql.query(query, function (err, data) {
        if (err) {
            console.log(err)
            return
        }

        res.render('editNote.html', {
            editNote: data[0]
        })
    })
})

/* 编辑笔记请求 */
router.post('/editNote', upload.single('edit'), function (req, res) {
    var body = req.body
    var file = req.file
    var id = body.id.replace(/"/g, '')
    var time = sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
    body.create_time = time

    var title = body.title
    var content = body.content
    var create_time = body.create_time
    var upload = file.destination + '/' + file.originalname
    var userID = req.session.data[0]

    var query = 'UPDATE notes SET title=' + mysql.escape(title) + ',content=' + mysql.escape(content) + ',create_time=' + mysql.escape(create_time) + ',upload=' + mysql.escape(upload) + ',userID=' + mysql.escape(userID.ID) + ' WHERE ID=' + mysql.escape(id)

    mysql.query(query, function (err, data) {
        if (err) {
            console.log(err)
            return
        }

        res.redirect('/')
    })
})

/* 渲染注册页面 */
router.get('/register', function (req, res) {
    res.render('register.html')
})

/* 注册请求 */
router.post('/register', function (req, res) {
    var body = req.body
    var email = body.email
    body.password = md5(body.password)
    var password = body.password

    var query = 'SELECT * FROM users WHERE email=' + mysql.escape(email)

    mysql.query(query, function (err, data) {
        if (err) {
            console.log(err)
            return
        }

        if (data.length == 0) {
            var query = 'INSERT users SET email=' + mysql.escape(email) + ',password=' + mysql.escape(password)
            mysql.query(query, function (err, data) {
                if (err) {
                    console.log(err)
                    return
                }

                res.redirect('/login')
            })
        }
        else {
            res.render('register.html', {
                message: '邮箱已存在，请直接登陆'
            })
        }
    })
})

/* 渲染登录页面 */
router.get('/login', function (req, res) {
    res.render('login.html')
})

/* 登录页面请求 */
router.post('/login', function (req, res) {
    var body = req.body

    var email = body.email
    body.password = md5(body.password)
    var password = body.password

    var query = 'SELECT * FROM users WHERE email=' + mysql.escape(email) + 'AND password=' + mysql.escape(password)

    mysql.query(query, function (err, data) {
        if (err) {
            console.log(err)
            return
        }

        if (data.length == 0) {
            res.render('login.html', {
                meaasge: '邮箱或密码错误'
            })
        } else {
            req.session.data = data
            res.redirect('/')
        }
    })
})

/* 退出登录请求 */
router.get('/logout', function (req, res) {
    req.session.data = null
    res.redirect('/')
})

/* 渲染查看笔记页面 */
router.get('/content', function (req, res) {

    var id = req.query.id.replace(/"/g, '')

    var query = 'SELECT * FROM notes WHERE ID=' + mysql.escape(id)

    mysql.query(query, function (err, data) {
        if (err) {
            console.log(err)
            return
        }

        res.render('content.html', {
            content: data[0]
        })
    })
})

/* 渲染个人信息页面 */
router.get('/mine', function (req, res) {
    res.render('mine.html')
})

/* 个人信息页面请求 */
router.post('/mine', upload.single('icon'), function (req, res) {
    var body = req.body
    var file = req.file
    var id = req.session.data

    var userName = body.userName
    var Introduction = body.Introduction

    var query = 'UPDATE users SET userName= ' + mysql.escape(userName) + ', Introduction= ' + mysql.escape(Introduction) + ' ,upload=' + mysql.escape(file.destination + '/' + file.originalname) + ' WHERE ID=' + mysql.escape(id[0].ID)

    mysql.query(query, function (err, data) {
        if (err) {
            console.log(err)
            return
        }

        res.redirect('/')
    })
})

/* 渲染编辑个人信息页面 */
router.get('/edit_mina', function (req, res) {
    var id = req.session.data

    var query = 'SELECT * FROM users WHERE ID=' + mysql.escape(id[0].ID)

    mysql.query(query, function (err, data) {
        if (err) {
            console.log(err)
            return
        }

        res.render('edit_mine.html', {
            getInfo: data[0]
        })
    })
})

/* 编辑个人信息请求 */
router.post('/edit_mina', upload.single('icon'), function (req, res) {

    var body = req.body
    var file = req.file
    var id = req.session.data

    var userName = body.userName
    var Introduction = body.Introduction

    var query = 'UPDATE users SET userName= ' + mysql.escape(userName) + ', Introduction= ' + mysql.escape(Introduction) + ' ,upload=' + mysql.escape(file.destination + '/' + file.originalname) + ' WHERE ID=' + mysql.escape(id[0].ID)

    mysql.query(query, function (err, data) {
        if (err) {
            console.log(err)
            return
        }

        res.redirect('/')
    })
})

/* 关于 */
router.get('/about', function (req, res) {
    res.render('about.html')
})

module.exports = router